<template lang="pug">
.list
  .material-section
    .material-section-title 材料一级分类：
    .material-section-list
      .material-section-item(v-for="(item, index) in firstCateList" :key="index")
        span(:class="!item.isSelected ? '' : 'is-selected'" @click.stop="clickCateItem(item, 'firstCateList', 'firstCateId')") {{ item.classificationName }}
  .material-section
    .material-section-title 材料二级分类：
    .material-section-list
      .material-section-item(v-for="(item, index) in secondCateList" :key="index")
        span(:class="!item.isSelected ? '' : 'is-selected'" @click.stop="clickCateItem(item, 'secondCateList', 'secondCateId')") {{ item.classificationName }}
  .material-section
    .material-section-title 分类图片设置：
    .material-section-list
      .material-image-body
        el-upload(
          action="#"
          :multiple="false"
          accept="image/png, image/jpeg, image/jpg, image/gif"
          ref="materialImgUpload"
          :file-list="imgList"
          list-type="picture"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleChange"
          :on-exceed="handleExceed"
          style="display: inline-block;"
        )
          .el-replace-btn(v-if="pictureUrl" slot="trigger") 更换图片
          .el-upload-btn(v-else slot="trigger")
            .iconfont.icon-tianjia
            .el-upload-btn-txt 点击上传
        i(v-if="pictureUrl" class="el-icon-circle-close" @click.stop="delPicture()")
        img(v-if="pictureUrl" :src="pictureUrl" style="width:320px; height:200px")

</template>

<script>
import { getChildrenClassifications, getSetList, setClassificationPicture, deleteClassificationPicture, FileUpload } from 'api'
let loading = ''
export default {
  name: 'materialImgManage',
  data () {
    return {
      firstCateList: [],
      secondCateList: [],
      firstCateId: '',
      secondCateId: '',
      fileId: '',
      pictureUrl: '',
      imgList: []
    }
  },
  methods: {
    async getCateList (key, id = 0) {
      try {
        const { ResultSet } = await this.$axios.post(getChildrenClassifications, { classificationId: id })
        this[key] = (ResultSet.userData.childrenNode || []).map(item => {
          item.isSelected = false
          return item
        })
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getCatePictureUrl () {
      try {
        const { ResultSet } = await this.$axios.post(getSetList, { classificationId: this.secondCateId })
        this.pictureUrl = ResultSet.userData.resultList[0].pictureUrl || ''
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async fileUpload (raw) {
      return new Promise(async (resolve, reject) => {
        try {
          let formData = new FormData()
          formData.append('Filedata', raw)
          formData.append("applicationId", 4)
          const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
          resolve({ ...ResultSet.Result[0] })
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    init () {
      this.getCateList('firstCateList')
    },
    async delPicture () {
      this.$confirm('是否确定删除该分类图片？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        //删除材料分类图片
        if (!this.secondCateId) {
          this.$message.error('请选择材料二级分类！')
          return
        }
        try {
          let query = {
            classificationId: this.secondCateId
          }
          await this.$axios.post(deleteClassificationPicture, { ...query })
          this.$message.success('删除成功！')
          this.fileId = ''
          this.pictureUrl = ''
          this.imgList = []
        } catch (err) {
          console.log(err)
          this.$message.error(err.message || err.ResultSet.errors)
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    clickCateItem (item, key, keyId) {
      let id = item.classificationId
      this[keyId] = id
      this[key] = this[key].map(el => {
        if(id === el.classificationId) {
          el.isSelected = true
        } else {
          el.isSelected = false
        }
        return el
      })
      if('firstCateId' === keyId) {
        //点击一级分类
        this.secondCateId = ''
        this.fileId = ''
        this.pictureUrl = ''
        this.imgList = []
        this.getCateList('secondCateList', id)
      }
      if('secondCateId' === keyId) {
        //点击二级分类
        this.fileId = ''
        this.imgList = []
        this.getCatePictureUrl()
      }
    },
    handleExceed () {
      this.$message.error('最多只能上传1张图片！')
    },
    handleChange (file, fileList) {
      if (file.size > 5 * 1024 * 1024) {
        let index = fileList.findIndex(item => item.uid === file.uid)
        fileList.splice(index, 1)
        this.$message.error('图片大小必须小于等于5MB！')
        return
      }
      this.$refs.materialImgUpload.clearFiles()
      this.imgList = fileList
      this.save()
    },
    async save () {
      if (!this.secondCateId) {
        this.$message.error('请选择材料二级分类！')
        return
      }
      if (!this.imgList || this.imgList.length == 0) {
        this.$message.error('请选择图片！')
        return
      }
      try {
        loading = this.$loading({
          lock: true,
          text: '保存中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const imgFile = await this.fileUpload(this.imgList[this.imgList.length - 1].raw)
        this.fileId = imgFile.fileId
        this.pictureUrl = imgFile.fileUrl
        this.imgList = []

        let query = {
          classificationId: this.secondCateId,
          pictureId: this.fileId
        }
        await this.$axios.post(setClassificationPicture, { ...query })
        this.$message.success('保存成功！')
        this.getCatePictureUrl()
        setTimeout(() => {
          loading.close()
        }, 1000)
      } catch (err) {
        setTimeout(() => {
          loading.close()
        }, 1000)
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.init()
    })
  }
}
</script>

<style lang="scss" scoped>
.list {
  width: 100%;
  min-height: 100%;
  background: #FFFFFF;
  border: 1px solid #F3F3F4;
  box-sizing: border-box;
  box-shadow: 0px 4px 0px #F3F3F4;
  border-radius: 10px;
  padding: 0 40px;
}
.material-section {
  padding: 16px 0;
  display: flex;
}
.material-section-title {
  font-size: 16px;
  line-height: 24px;
  color: #3E4373;
  margin-right: 16px;
}
.material-section-list {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.material-section-item {
  padding-right: 24px;
  padding-bottom: 24px;
  span {
    display: inline-block;
    font-size: 14px;
    line-height: 24px;
    color: #B2B4C7;
    background: #FFFFFF;
    border: 1px solid #B2B4C7;
    border-radius: 3px;
    padding: 3px 16px;
    cursor: pointer;
    &:hover {
      color: #EE0A24;
      border: 1px solid #EE0A24;
    }
    &.is-selected {
      color: #F3F3F4;
      background: #EE0A24;
      border: 1px solid #EE0A24;
      &:hover {
        color: #B2B4C7;
      }
    }
  }
}
.material-image-body {
  position: relative;
}

.el-upload-btn {
  width: 320px;
  height: 200px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #B2B4C7;
  border: 1px dashed #c0ccda;
  &:hover {
    border-color: #FF708B;
    color: #FF708B;
  }
  .iconfont {
    font-size: 20px;
    font-weight: bold;
  }
  .el-upload-btn-txt {
    font-size: 14px;
  }
}
.el-icon-circle-close {
  position: absolute;
  top: -10px;
  right: -10px;
  z-index: 1;
  font-size: 20px;
  color: #EE0A24;
  cursor: pointer;
}
.el-replace-btn {
  width: 320px;
  height: 28px;
  background: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 14px;
  line-height: 28px;
  text-align: center;
  cursor: pointer;
  position: absolute;
  bottom: 0;
  z-index: 1;
}
</style>
